/* -*-  Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2010 University College London 
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Author: Joao Taveira Araujo <j.araujo@ucl.ac.uk>
 */

#include "ns3/log.h"
#include "ns3/packet.h"
#include "ns3/object-vector.h"
#include "ns3/node.h"
#include "ns3/ipv4-route.h"
#include "ipv4-react-routing.h"
#include "ns3/trace-source-accessor.h"
#include "ns3/uinteger.h"

NS_LOG_COMPONENT_DEFINE ("Ipv4ReactRouting");

using std::make_pair;

namespace ns3 {

NS_OBJECT_ENSURE_REGISTERED (Ipv4ReactRouting);

TypeId
Ipv4ReactRouting::GetTypeId (void)
{
  static TypeId tid = TypeId ("ns3::Ipv4ReactRouting")
    .SetParent<Ipv4RoutingProtocol> ()
    .AddConstructor<Ipv4ReactRouting> ()
    .AddAttribute ("FlowSplitMin", "Minimum percentage of flows for a given path.",
                   DoubleValue (0.01),
                   MakeDoubleAccessor (&Ipv4ReactRouting::m_flowSplitMin),
                   MakeDoubleChecker<double> ())
    .AddAttribute ("UpdateLexInterval", "Time interval between update of loss average.",
                   TimeValue (Seconds (2.0)),
                   MakeTimeAccessor (&Ipv4ReactRouting::m_updateLexInterval),
                   MakeTimeChecker ())
    .AddAttribute ("UpdatePrefInterval", "Time interval between update of flowSplit.",
                   TimeValue (Seconds (10.0)),
                   MakeTimeAccessor (&Ipv4ReactRouting::m_updatePrefInterval),
                   MakeTimeChecker ())
     .AddAttribute ("FlowSplitUpdateFunc", "A callback to the function that do the update of flowSplit",
                   CallbackValue (),
                   MakeCallbackAccessor (&Ipv4ReactRouting::m_flowSplitUpdate),
                   MakeCallbackChecker ())
   .AddTraceSource ("UpdatePref", "Update flowSplit values.",
                  MakeTraceSourceAccessor (&Ipv4ReactRouting::m_traceUpdate))
    ;
  return tid;
}

Ipv4ReactRouting::Ipv4ReactRouting () 
: m_ipv4 (0)
{
  NS_LOG_FUNCTION_NOARGS ();
  UpdateLexStats();
  UpdatePrefStats();
  
}
 
void
Ipv4ReactRouting::UpdateLexStats()
{
  for (RouteTableI i = m_routeList.begin (); i != m_routeList.end (); i++) 
  {
    (*i)->Timestep();
    m_traceUpdate(*i);
  }
  Simulator::Schedule( m_updateLexInterval, &Ipv4ReactRouting::UpdateLexStats, this);
}

void
Ipv4ReactRouting::UpdatePrefStats()
{
  //only iterate over default routes as we will update flowSplit for each NETWORK ADDRESS
  //default table contains one instance of every destination network
  for (RouteTableI i = m_defaultRoutes.begin (); i != m_defaultRoutes.end (); i++) 
  {
    Ipv4Address entry = (*i)->GetDestNetwork ();
    UpdatePref(&entry);
  }

  Simulator::Schedule( m_updatePrefInterval, &Ipv4ReactRouting::UpdatePrefStats, this);
}


void
Ipv4ReactRouting::UpdatePref(Ipv4Address *entry)
{
  //all destinations are contained in default routing table
  Ptr<Ipv4ReactTableEntry> route = 0;
  RouteTableI routeIter;
  RouteTable  availableRoutes;

  double sumRexmit  = 0;
  double sumTxmit = 0;
  double sumTheta = 0; // txmit^2 / rexmit

  //for each interface table, get routes, calculate totals 
  for ( uint32_t i=0 ; i<m_ipv4->GetNInterfaces() ; i++ )
  {
    //search for address, add entry to list
    route = LookupReact (*entry, &m_routeList, i);
    if( route ) {
      availableRoutes.push_back(route);
      sumTxmit += route->GetWghtTxmit();
      sumTheta += route->GetWghtTheta();

      //to be removed
      sumRexmit += route->GetWghtRexmit();
    }
  }

  int numPaths = availableRoutes.size();

  // single route, no choice.
  if (numPaths == 1)
  {
    route = availableRoutes.front();
    route->SetFlowSplit(1);
    return;
  }

  double equalisation = 1.0 / numPaths;

  if (!sumTxmit)
  {
    for( routeIter = availableRoutes.begin(); routeIter != availableRoutes.end(); routeIter++ ) 
    {
      (*routeIter)->SetFlowSplit(equalisation);
    }
    //std::cout << "\tequalisation " << equalisation<< "\tloss " << std::endl;
    return;
  }

  double lossdrivenFrac   = 1.0 / sumTheta;
  double conservativeFrac = 1.0 / sumTxmit;
  double conservative;
  double lossdriven;

  double m_be = 0.0;
  double m_bc = 0.0;
  double m_bl = 1.0;


  for( routeIter = availableRoutes.begin(); routeIter != availableRoutes.end(); routeIter++ ) 
  {
    route = (*routeIter);

    conservative  = route->GetWghtTxmit() * conservativeFrac;
    lossdriven    = route->GetWghtTheta() * lossdrivenFrac;;

    double fSplit  = m_be * equalisation + m_bc * conservative + m_bl * lossdriven;

    route->SetFlowSplit(fSplit);
    //std::cout << route->GetWghtTxmit() << "\t" << route->GetWghtRexmit() << std::endl;
    //std::cout << "\tlossdriven " << lossdriven << "\tconservative " << conservative << "\tequalisation " << equalisation<< "\tloss " <<  route->GetWghtLoss()  << "\tsplit " << fSplit << std::endl;
  }

  /*
  //double sumFlowSplit = m_flowSplitUpdate(&availableRoutes, sumTxmit, sumRexmit );
  //double sumFlowSplit = 1.0;
  double currentFlowSplit;

  for( routeIter = availableRoutes.begin(); routeIter != availableRoutes.end(); routeIter++ )
  {
    route = (*routeIter);
    //normalize flow split
    if(sumFlowSplit) {
      currentFlowSplit = route->GetFlowSplit();
      route->SetFlowSplit(currentFlowSplit/sumFlowSplit);
    }
    NS_LOG_FUNCTION("FlowSplit is " << route->GetFlowSplit() << " " << route->GetWghtLoss() );
  }
  */

}


Ptr<Ipv4ReactTableEntry>
Ipv4ReactRouting::AddDefaultNetworkRouteTo (Ipv4Address network, 
                                          Ipv4Mask networkMask, 
                                          uint32_t interface)
{
  return AddNetworkRouteTo(network, networkMask, interface, true);

}


Ptr<Ipv4ReactTableEntry>
Ipv4ReactRouting::AddNetworkRouteTo (Ipv4Address network, 
                                      Ipv4Mask networkMask, 
                                      uint32_t interface, bool def)
{
  NS_LOG_FUNCTION_NOARGS ();

  Ptr<Ipv4ReactTableEntry> route = CreateObject<Ipv4ReactTableEntry> (network, networkMask, interface);

  m_routeList.push_back (route);

  if( def )
    m_defaultRoutes.push_back (route);

  //add as External interface if not already
  if(!IsExternalInterface(interface))
  {
  //NS_LOG_INFO(network << " " << interface);
    m_externalInterfaces.push_back(interface);
    m_externalInterfaces.sort();
  }

  UpdatePref(&network);
  return route;
}

Ptr<Ipv4ReactTableEntry>
Ipv4ReactRouting::LookupReact (Ipv4Address dest, RouteTable* routeTable, uint32_t interface )
{
  NS_LOG_FUNCTION_NOARGS ();
  NS_ASSERT(routeTable);

  uint16_t longest_mask = 0;
  Ptr<Ipv4ReactTableEntry> selectedRoute = 0;

  for (RouteTableI i = routeTable->begin (); 
      i != routeTable->end (); i++) 
      {
        //only check for routes on specific interface
        if( (*i)->GetInterface() == interface  )
        {
          Ipv4Mask mask = (*i)->GetDestNetworkMask ();
          uint16_t masklen = mask.GetPrefixLength ();
          Ipv4Address entry = (*i)->GetDestNetwork ();
          NS_LOG_LOGIC ("Searching for route to " << dest << ", checking against route to " << entry << "/" << masklen);
          if (mask.IsMatch (dest, entry)) 
          {
            NS_LOG_LOGIC ("Found global network route " << *i << ", mask length " << masklen );
            if (masklen < longest_mask) // Not interested if got shorter mask
            {
              NS_LOG_LOGIC ("Previous match longer, skipping");
              continue;
            }
          longest_mask = masklen;
          selectedRoute = *i;
          } 
        }
      }

  return selectedRoute;
}


Ptr<Ipv4ReactTableEntry>
Ipv4ReactRouting::LookupReact (Ipv4Address dest, uint8_t path)
{
  NS_LOG_FUNCTION_NOARGS ();
  Ptr<Ipv4ReactTableEntry> selectedRoute = 0;

  if (path)
  {
    selectedRoute = LookupReact ( dest, &m_routeList, path);
  }

  return selectedRoute;
}
 
uint32_t
Ipv4ReactRouting::SelectRoute (Ipv4Address dest)   
{
  NS_LOG_FUNCTION_NOARGS ();

  Ptr<Ipv4ReactTableEntry> selectedRoute = 0;
  Ptr<Ipv4ReactTableEntry> currentRoute = 0;

  double maxToken = 0;
  double curToken = 0;
  int hasToken = 0;

  //get all routes, choose route with highest token
  for ( uint32_t i=0 ; i<m_ipv4->GetNInterfaces() ; i++ )
  {
    currentRoute = LookupReact (dest, &m_routeList, i);

    if(currentRoute)
    {
      curToken = currentRoute->IncrementTokenCount();

      if(!hasToken) {
        hasToken = 1;
        maxToken = curToken;
        selectedRoute = currentRoute;
      }
      else if ( maxToken < curToken ) {
        maxToken = curToken;
        selectedRoute = currentRoute;
      }
    }
  }

  if(selectedRoute)
  {
    NS_LOG_INFO( "maxToken" << maxToken << " using "<< selectedRoute->GetInterface() << '\n' );
    // update token data for selected path
    selectedRoute->DecrementTokenCount();
    return selectedRoute->GetInterface();
  }

  NS_LOG_INFO("No ROUTE?");
  return 0;
}

uint32_t 
Ipv4ReactRouting::GetNRoutes (void)
{
  NS_LOG_FUNCTION_NOARGS ();
  return m_routeList.size ();
}

Ptr<Ipv4ReactTableEntry>
Ipv4ReactRouting::GetRoute (uint32_t index)
{
  NS_LOG_FUNCTION_NOARGS ();
      uint32_t tmp = 0;
  for (RouteTableI j = m_routeList.begin (); j != m_routeList.end (); j++) 
        {
          if (tmp  == index)
          {
            return (*j);
          }
          tmp++;
        }
  NS_ASSERT (false);
  // quiet compiler.
  return 0;
}


void
Ipv4ReactRouting::RemoveRoute( RouteTable* table, Ptr<Ipv4ReactTableEntry> entry)
{
  for (RouteTableI j = table->begin (); j != table->end (); j++) 
  {
    if ( (*j) == entry )
    {
      table->erase(j);
      return;
    }
  }

  return;
}

void 
Ipv4ReactRouting::RemoveRoute (uint32_t index)
{
  NS_LOG_FUNCTION_NOARGS ();
  uint32_t tmp = 0;
  for (RouteTableI j = m_routeList.begin (); 
       j != m_routeList.end (); 
       j++) 
    {
      if (tmp == index)
      {
        //check if entry exists in default
        RemoveRoute(&m_defaultRoutes, (*j) );

        m_routeList.erase (j);
        return;
      }
      tmp++;
    }
  NS_ASSERT (false);
}

Ptr<Ipv4Route> 
Ipv4ReactRouting::RouteOutput (Ptr<Packet> p, const Ipv4Header &header, Ptr<NetDevice> oif, Socket::SocketErrno &sockerr)
{
  return 0;
}

bool 
Ipv4ReactRouting::RouteInput  (Ptr<const Packet> p, const Ipv4Header &ipHeader, Ptr<const NetDevice> idev,
                             UnicastForwardCallback ucb, MulticastForwardCallback mcb,
                             LocalDeliverCallback lcb, ErrorCallback ecb)
{
  NS_LOG_FUNCTION (this << p << ipHeader << ipHeader.GetSource () << ipHeader.GetDestination () << idev);

  NS_ASSERT (m_ipv4 != 0);
  // Check if input device supports IP 
  NS_ASSERT (m_ipv4->GetInterfaceForDevice (idev) >= 0);
  uint32_t iif = m_ipv4->GetInterfaceForDevice (idev); 

  // React only handles unicast
  if (ipHeader.GetDestination ().IsMulticast () || (ipHeader.GetDestination ().IsBroadcast ()))
    {
      return false;
    }

  Ipv4HeaderReflexTag rtag;
  rtag.GetIpv4Header (&ipHeader);

  // check if re-ecn capable
  if ( ! rtag.GetReflex() )
    {
      return false;
    }
  else 
    {
      NS_LOG_LOGIC ("Unicast destination, re-ecn enabled");
    }

  // Check if input device supports IP forwarding
  if (m_ipv4->IsForwarding (iif) == false)
    {
      NS_LOG_LOGIC ("Forwarding disabled for this interface");
      ecb (p, ipHeader, Socket::ERROR_NOROUTETOHOST);
      return false;
    }

  Ptr<Ipv4ReactTableEntry> selectedRoute;

  if ( IsExternalInterface(iif) ) 
  {

    //for incoming SYN/ACK packets to local domain piggy back route information
    if ( rtag.GetReflex() == Ipv4HeaderReflexTag::FNE )
    {
        //reverse lookup
        uint32_t path = SelectRoute (ipHeader.GetSource ());
        if ( path )
        {
          NS_LOG_LOGIC ("Tagging incoming packet with route to " << ipHeader.GetSource() << " with path " << path);
          Ipv4HeaderPathTag tag;
          tag.SetPath(path);
          p->AddPacketTag(tag);
        }
    }

    //retrieve default path for this packet
    return false;
  }
  else {
    //if packet from internal interface (may or may not be outgoing)
    //NS_LOG_LOGIC ("From ingress link");

    // for packets with codepoint, verify table and forward.
    Ipv4HeaderPathTag ptag;
    ptag.GetIpv4Header(&ipHeader);

    uint8_t dscp = ptag.GetPath();
    selectedRoute = LookupReact (ipHeader.GetDestination (), dscp);
    
    // we don't clear dscp right now
    if (dscp) {
      p->AddPacketTag(ptag);
    }
  }


  // Next, try to find a route
  if (selectedRoute)
  {
    Ptr<Ipv4Route> rtentry = 0;
    uint32_t interfaceIdx = selectedRoute->GetInterface ();
    //uint32_t interfaceIdx = 10;
    //std::cout << "Selected Route" << '\n';
    rtentry = Create<Ipv4Route> ();
    rtentry->SetOutputDevice (m_ipv4->GetNetDevice (interfaceIdx));

    //NS_LOG_LOGIC ("Found unicast destination- calling unicast callback");
    ucb (rtentry, p, ipHeader);  // unicast forwarding callback
    //update stats

    selectedRoute->CountLex(rtag.GetReflex(), p->GetSize());

    return true;
  }
  else
  {
    NS_LOG_LOGIC ("Did not find unicast destination- returning false");
    return false; // Let other routing protocols try to handle this
  }
}

Ipv4ReactRouting::~Ipv4ReactRouting ()
{
  NS_LOG_FUNCTION_NOARGS ();
}

void
Ipv4ReactRouting::DoDispose (void)
{
  NS_LOG_FUNCTION_NOARGS ();

  for (RouteTableI j = m_defaultRoutes.begin (); j != m_defaultRoutes.end (); j = m_defaultRoutes.erase (j))
    ;

  for (RouteTableI j = m_routeList.begin (); j != m_routeList.end (); j = m_routeList.erase (j))
    ;

  m_ipv4 = 0;
  Ipv4RoutingProtocol::DoDispose ();
}

void 
Ipv4ReactRouting::NotifyInterfaceUp (uint32_t i)
{
}

void 
Ipv4ReactRouting::NotifyInterfaceDown (uint32_t i)
{
  // Remove all static routes that are going through this interface
  uint32_t j = 0;
  while (j < GetNRoutes())
    {
      Ptr<Ipv4ReactTableEntry> route = GetRoute (j);
      if (route->GetInterface () == i)
        {
          RemoveRoute (j);
        }
      else
        {
          j++;
        }
    }
}

void 
Ipv4ReactRouting::NotifyAddAddress (uint32_t interface, Ipv4InterfaceAddress address)
{
  NS_LOG_FUNCTION (this << interface);
}
void 
Ipv4ReactRouting::NotifyRemoveAddress (uint32_t interface, Ipv4InterfaceAddress address)
{
  if (!m_ipv4->IsUp (interface))
    {
      return;
    }
  Ipv4Address networkAddress = address.GetLocal ().CombineMask (address.GetMask ());
  Ipv4Mask networkMask = address.GetMask ();
  // Remove all static routes that are going through this interface
  // which reference this network
  for (uint32_t j = 0; j < GetNRoutes (); j++)
    {
      Ptr<Ipv4ReactTableEntry> route = GetRoute (j);
      if (route->GetInterface () == interface &&
          route->GetDestNetwork () == networkAddress &&
          route->GetDestNetworkMask () == networkMask)
        {
          RemoveRoute (j);
        }
    }
}

void 
Ipv4ReactRouting::SetIpv4 (Ptr<Ipv4> ipv4)
{
  NS_LOG_FUNCTION (this << ipv4);
  NS_ASSERT (m_ipv4 == 0 && ipv4 != 0);
  m_ipv4 = ipv4;
}

bool
Ipv4ReactRouting::IsExternalInterface(uint32_t ifnum)
{
  for (std::list<uint32_t>::iterator j = m_externalInterfaces.begin (); j != m_externalInterfaces.end (); j++) 
  {
    if( ifnum == (*j) ) {
      return true;
    }
  }
  return false;
}
 
}//namespace ns3
